package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"time"
	"warehouse-management/models/cache"
	"warehouse-management/models/mysql"
)

type WarehouseController struct {
	beego.Controller
}

func (c *WarehouseController) Add() {
	warehouseUid := c.GetString("warehouseUid")
	source := c.GetString("source")
	warehouseName := c.GetString("warehouseName")
	warehouseNum, _ := c.GetInt64("warehouseNum")
	price, _ := c.GetFloat("price")
	name := c.GetString("name")

	var warehouse mysql.Warehouse
	warehouse.WarehouseUid = warehouseUid
	warehouse.Source = source
	warehouse.WarehouseName = warehouseName
	warehouse.WarehouseNum = warehouseNum
	warehouse.Price = price
	warehouse.Name = name

	err := warehouse.WarehouseAdd()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"msg":  "新增失败",
			"code": 500,
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"msg":  "新增成功",
		"code": 200,
	}
	c.ServeJSON()
	return
}

func (c *WarehouseController) List() {
	var warehouse mysql.Warehouse
	page, _ := c.GetInt64("page", 1)
	pageSize, _ := c.GetInt64("pageSize", 5)
	id, _ := c.GetInt64("id")
	warehouseName := c.GetString("warehouseName")
	query := mysql.DB.Model(&warehouse)
	if warehouseName != "" {
		query = query.Where("warehouseName = ?", warehouseName).Find(&warehouse)
	}
	if id != 0 {
		query = query.Where("id = ?", id).Find(&warehouse)
	}

	var count int64
	query.Count(&count)

	sum := int(math.Ceil(float64(count) / float64(pageSize)))
	offrest := (page - 1) * pageSize
	up := page - 1
	if up < 1 {
		up = 1
	}
	down := page + 1
	if down > int64(sum) {
		down = int64(sum)
	}
	var warehouses []mysql.Warehouse
	err := query.Offset(int(offrest)).Limit(int(pageSize)).Find(&warehouses).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"msg":  "展示失败",
			"code": 500,
		}
		c.ServeJSON()
		return
	}
	pageData := map[string]interface{}{
		"up":   up,
		"down": down,
		"sum":  sum,
		"data": warehouses,
	}
	cache.Rdb.Set(cache.Ctx, "list", warehouses, time.Minute*20)
	c.Data["json"] = map[string]interface{}{
		"msg":  "展示成功",
		"code": 200,
		"data": pageData,
	}
	c.ServeJSON()
	return

}
